package com.xiaoyu.lanling.feature.invite.data

import `in`.srain.cube.request.FailData
import `in`.srain.cube.request.JsonData
import `in`.srain.cube.request.RequestDefaultHandler
import `in`.srain.cube.views.list.PagedListDataModelWithRequestTag
import com.xiaoyu.base.net.RequestCreator
import com.xiaoyu.lanling.common.config.HttpConfig
import com.xiaoyu.lanling.event.invite.earning.InviteEarningListEvent
import com.xiaoyu.lanling.feature.invite.model.InviteEarnItem

class InviteEarningListData : PagedListDataModelWithRequestTag<InviteEarnItem, Any>() {
    val tag = Any()
    override fun doQueryData() {
        RequestCreator.create(InviteEarningListEvent::class.java)
                .setRequestUrl(HttpConfig.LANLING_INVITE_EARN_LIST)
                .appendQueryDataTo(listPageInfo)
                .setPostEventWhenFail(true)
                .setRequestHandler(object : RequestDefaultHandler<InviteEarningListEvent, JsonData>() {

                    override fun onRequestFail(failData: FailData?) {
                        InviteEarningListEvent(requestTag).fail(null).post()
                    }

                    override fun processOriginData(originData: JsonData): InviteEarningListEvent {
                        val rawData = originData.optJson("data")
                        val rawList = rawData.optJson("list").toList()
                        val list = mutableListOf<InviteEarnItem>()
                        val preLen = listPageInfo.dataList.size
                        for ((index, item) in rawList.withIndex()) {
                            list.add(InviteEarnItem(1, item))
                        }
                        updateResult(rawData, list)
                        return InviteEarningListEvent(requestTag)
                    }

                    override fun onRequestFinish(event: InviteEarningListEvent?) {
                        event?.post()
                    }
                })
                .enqueue()
    }

    override fun getRequestTag(): Any {
        return tag
    }
}